package com.yunpai.thread;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

/**
 * 创建线程方式三 jdk1.5新增 实现Callable接口
 */
//1.创建一个实现Callable的实现类
public class ThreadTypeTree implements Callable {
    int count = 0;

    //2.实现call方法,将此线程执行的操作声明在call方法内
    @Override
    public Object call() throws Exception {

        for (int sum = 100; sum >= 0; sum--) {
            if (sum % 2 == 0) {
                System.out.println(Thread.currentThread().getName() + ":" + sum);
                count += sum;
            }
        }
        return count;
    }

    public static void main(String[] args) {
        //3.创建Callable接口实现类的对象
        ThreadTypeTree threadTypeTree = new ThreadTypeTree();
        //4.将Callable接口实现类的对象传入FutureTask构造器中,创建FutureTask对象
        FutureTask futureTask = new FutureTask(threadTypeTree);
        //5.将FutureTask对象传入Thread构造器中,创建对象,并调用start
        Thread thread = new Thread(futureTask);
        thread.setName("线程一");
        thread.start();
        try {
            //6.获取Callable中call方法的返回值
            //get返回值即为futureTask构造器参数Callable实现类重写的call返回值
            Object sum = futureTask.get();
            System.out.println(sum);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
    }
}
